package com.sxb.spike.rabbitmq;

import com.sxb.spike.pojo.User;
import com.sxb.spike.service.IGoodsService;
import com.sxb.spike.service.IOrderService;
import com.sxb.spike.utils.JsonUtil;
import com.sxb.spike.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

/**
 * @author 沈小白
 * @project spike
 * @description
 * @date 2023/6/28 15:11:33
 */
@Service
@Slf4j
public class MQReceiver {

    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IOrderService orderService;

    @RabbitListener(queues = "seckillQueue")
    public void receive(String message) {
        log.info("QUEUE接收消息：" + message);
        SeckillMessage seckillMessage = JsonUtil.jsonStr2Object(message, SeckillMessage.class);
        Long goodsId = seckillMessage.getGoodsId();
        User user = seckillMessage.getUser();
        GoodsVo goods = goodsService.findGoodsVoByGoodsId(goodsId);
        // 判断库存
        if (goods.getStockCount() < 1) {
            return;
        }
        String seckillOrderJson = (String) redisTemplate.opsForValue().get("order:" + user.getId() + ":" + goodsId);
        if (!StringUtils.isEmpty(seckillOrderJson)) {
            return;
        }
        orderService.seckill(user, goods);
    }

/*    @RabbitListener(queues = "queue_header02")
    public void receive02(Message msg) {
        log.info("QUEUE02接收Message对象：" + msg);
        log.info("QUEUE02接收消息：" + new String(msg.getBody()));
    }*/
}
